var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var app = express();
var roleList = require('../../../data/role-data');
var _ = require('underscore');
var pagination = require('../../../utils/pagination')();
var MessageModel = require("../../../model/iotek-message")();

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.raw()); // for parsing application/raw
app.use(bodyParser.text()); // for parsing application/text
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

/* GET home page. */

router.get('/', function (request, response, next) {
    var type = +request.query['type'];
    var pn = +request.query['pn'];
    var ps = +request.query['ps'];
    if (!(type && pn && ps)) {
        response.json(roleList);
    } else {
        var filteredList = _.filter(roleList, function (role) {
            return role.type == type;
        });
        var resultList = pagination(pn, ps, filteredList);
        var paginationInfo = {
            totalPage: Math.ceil(filteredList.length / ps),
            totalItems: filteredList.length,
            pn: pn,
            ps: ps,
            resultList: resultList
        };
        response.json(paginationInfo);
    }

});

router.delete('/:id', function (request, response, next) {
    try {
        var id = +request.params['id'];
        var deletedList = _.reject(roleList, function (role) {
            return role.id == id;
        });
        roleList = deletedList;
    } catch (e) {
        response.json(new MessageModel('FAILED', "删除失败了", "角色并没有删除！"));
        return;
    }
    response.json(new MessageModel('SUCCESS', "删除成功", "角色已经删除成功了！"));
});

router.put('/',function (request, response) {
    var type = +request.body['type'];
    var newName = request.body['newName'];
    var errorMessages = [];
    try {
        if(!!!type) {
            errorMessages.push("没有选择角色类型！");
        }
        if(!!!newName) {
            errorMessages.push("角色名字必须填写！");
        }
        if(!!errorMessages.length) {
            throw errorMessages.join(",");
        } else {
            var newRole = executeAddRole(type, newName);
        }
    } catch (e) {
        response.json(new MessageModel("FAILED", "添加失败", e));
        return;
    }
    response.json(new MessageModel("SUCCESS", "添加成功", newRole));
});

router.post('/',function (request, response) {
    var id = +request.body['id'];
    var newName = request.body['newName'];
    var type = +request.body['type']
    var findFlag = false;
    for(var index in roleList) {
        var role = roleList[index];
        if(role.id == id) {
            role.name = newName;
            role.type = type;
            findFlag = true;
            break;
        }
    }
    if(!findFlag) {
        response.json(new MessageModel("FAILED", "更新数据失败", "更新失败了， 原因是没找到id对应的角色"));
    } else {
        response.json(new MessageModel("SUCCESS", "更新成功", "更新成功了！！"));
    }
});

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

function executeAddRole(type, roleName) {
    var maxRole = _.max(roleList, function (role) {
        return role.id
    });
    var newObj = {
        "id" : ++maxRole.id,
        "name":roleName,
        "description":null,
        "type":type,
        "createUser":910,
        "updateUser":910,
        "createTime": new Date().Format("yyyy-MM-dd hh:mm:ss"),
        "updateTime": new Date().Format("yyyy-MM-dd hh:mm:ss")
    };
    roleList.unshift(newObj);
    return newObj;
}

module.exports = router;
